<?php

/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#namespace tehframework\storage;

#use \InvalidArgumentException;

class TransientStorage implements Storage
{
	/**
	 * @var array<string,mixed>
	 */
	private $dataMap;
	
	/**
	 * @param  array<string,mixed> $dataMap
	 */
	public function __construct(array $dataMap = array())
	{
		$this->dataMap = $dataMap;
	}
	
	/**
	 * @return array<string,mixed>
	 */
	public function getDataMap()
	{
		return $this->dataMap;
	}
	
	/**
	 * Stores the {@link $data} under {@link $id}.
	 * 
	 * @param  string $id
	 *         A non-empty, unique identifier of the data.
	 * @param  mixed $data
	 *         A data to store. Can not be NULL.
	 * @return Storage
	 * @throws InvalidArgumentException
	 *         If $id is NULL or empty.
	 * @throws InvalidArgumentException
	 *         If $data is NULL.
	 */
	public function store($id, $data)
	{
		if (($id === null) || ($id === ''))
		{
			throw new InvalidArgumentException('ID can not be NULL or empty.');
		}
		
		if ($data === null)
		{
			throw new InvalidArgumentException('Data can not be NULL.');
		}
		
		$this->dataMap[$id] = $data;
		
		return $this;
	}
	
	/**
	 * Returns the data stored under {@link $id}.
	 * 
	 * @param  string $id
	 *         A non-empty, unique identifier of the data.
	 * @return mixed
	 *         The data stored under $id or NULL if it did not exist.
	 */
	public function restore($id)
	{
		return isset($this->dataMap[$id]) ? $this->dataMap[$id] : null;
	}
	
	/**
	 * Removes the data stored under {@link $id}.
	 * 
	 * @param  string $id
	 *         A non-empty, unique identifier of the data.
	 * @return Storage
	 */
	public function delete($id)
	{
		if (isset($this->dataMap[$id]))
		{
			unset($this->dataMap[$id]);
		}
		
		return $this;
	}
	
	/**
	 * Removes all stored data.
	 * 
	 * @return Storage
	 */
	public function clear()
	{
		$this->dataMap = array();
		
		return $this;
	}
}